package dispatch

import (
	"fmt"
	"go-barcode/internal/api"
	"go-barcode/pkg/tools"
	"path/filepath"
	"strings"
)

type Dispatcher struct {
	Creator api.CodeCreator
	Reader  api.CodeReader
}

//创建
func (d *Dispatcher) Create(sourceFile, basePath string, img api.ImageCode) error {
	if d.Creator == nil {
		return fmt.Errorf("对象未初始化")
	}
	lines, err := tools.ReadLine(sourceFile)
	if err != nil {
		return err
	}
	for value := lines.Front(); value != nil; value = value.Next() {
		content := string(value.Value.([]byte))
		content = strings.ReplaceAll(content, "\r", "")
		content = strings.ReplaceAll(content, "\n", "")
		if content == "" {
			continue
		}
		c := tools.DealPath(content, "^")
		if !strings.HasSuffix(basePath, string(filepath.Separator)) {
			basePath = fmt.Sprintf("%v%v", basePath, string(filepath.Separator))
		}
		imgPath := fmt.Sprintf("%v%s.png", basePath, c)
		err = d.Creator.Create(imgPath, content, img)
		if err != nil {
			return err
		} else {
			fmt.Printf("创建[%v]成功\n", content)
		}
	}
	return nil
}

//读取
func (d *Dispatcher) Read(filePath string) (string, error) {
	if d.Creator == nil {
		return "", fmt.Errorf("对象未初始化")
	}
	return "", nil
}
